package logservice

import (
	"fmt"
	"gitee.com/amoyx/cloud-provider/pkg/cloud/huawei/models"
	lts "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2"
	"github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2/model"
	regionv2 "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/lts/v2/region"
	"strconv"
	"time"
)

type LogCollectGetter interface {
	LogCollect(region string) LogCollectInterface
}

type LogCollectInterface interface {
	CreateCollectConfig(args models.LogCollectRequest) (id string, err error)
}

type logCollect struct {
	client *lts.LtsClient
}

func newCollect(log *LogService, region string) LogCollectInterface {
	_client := lts.NewLtsClient(
		lts.LtsClientBuilder().
			WithRegion(regionv2.ValueOf(region)).
			WithCredential(log.credentials).
			Build())
	return &logCollect{
		client: _client,
	}
}

// CreateCollectConfig 创建日志采集
func (c logCollect) CreateCollectConfig(args models.LogCollectRequest) (id string, err error) {
	request := &model.CreateAccessConfigRequest{}
	logInfoBody := &model.AccessConfigBaseLogInfoCreate{
		LogGroupId:  args.LogGroupId,
		LogStreamId: args.LogStreamId,
	}
	modeSingle := model.GetAccessConfigFormatSingleCreateModeEnum().SYSTEM
	valueSingle := strconv.FormatInt(time.Now().UnixMilli(), 10)
	singleFormat := &model.AccessConfigFormatSingleCreate{
		Mode:  &modeSingle,
		Value: &valueSingle,
	}
	formatAccessConfigDetail := &model.AccessConfigFormatCreate{
		Single: singleFormat,
	}
	stdoutAccessConfigDetail := true
	stderrAccessConfigDetail := true
	pathTypeAccessConfigDetail := model.GetAccessConfigDeatilCreatePathTypeEnum().CONTAINER_STDOUT
	namespaceRegexAccessConfigDetail := args.Namespace
	accessConfigDetailBody := &model.AccessConfigDeatilCreate{
		Format:         formatAccessConfigDetail,
		Stdout:         &stdoutAccessConfigDetail,
		Stderr:         &stderrAccessConfigDetail,
		PathType:       &pathTypeAccessConfigDetail,
		NamespaceRegex: &namespaceRegexAccessConfigDetail,
	}
	clusterIdCreateAccessConfigRequestBody := args.ClusterId
	logSplitCreateAccessConfigRequestBody := true
	request.Body = &model.CreateAccessConfigRequestBody{
		ClusterId:          &clusterIdCreateAccessConfigRequestBody,
		LogSplit:           &logSplitCreateAccessConfigRequestBody,
		LogInfo:            logInfoBody,
		AccessConfigDetail: accessConfigDetailBody,
		AccessConfigType:   model.GetCreateAccessConfigRequestBodyAccessConfigTypeEnum().K8_S_CCE,
		AccessConfigName:   args.Name,
	}
	response, err := c.client.CreateAccessConfig(request)
	if err != nil {
		fmt.Printf("[LogService] 创建日志采集失败, %+v", err)
		return
	}
	return *response.AccessConfigId, nil
}
